package cn.cherry.mybatis.pietoken;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: SongTiankai
 * @Description: 全局统一用户上下文管理
 * @Date: 2023/12/31 21:12
 * @Version: 1.0
 */
@Slf4j
@Component
public class LoginUserContext {
    private static ConcurrentHashMap<String,LoginUser> LOGIN_USER_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>();


    /**
     * 登录用户
     * @param loginUser
     */
    public static void setLoginUser(LoginUser loginUser){
        LOGIN_USER_CONCURRENT_HASH_MAP.put(loginUser.getToken(), loginUser);
    }

    /**
     * 获取用户
     * @param token
     * @return
     */
    public static LoginUser getLoginUser(String token){
        return LOGIN_USER_CONCURRENT_HASH_MAP.get(token);
    }

    /**
     * 移除登录用户
     * @param token
     */
    public static void delLoginUser(String token){
        LoginUser loginUser = getLoginUser(token);
        if(loginUser != null){
            LOGIN_USER_CONCURRENT_HASH_MAP.remove(token);
        }else {
            log.info("移除用户不存在！");
        }

    }

    /**
     * 获取上下文用户
     * @return
     */
    public static LoginUser getLoginUser(){
        return LoginUserThreadLocal.getLocalUser();
    }

}
